package com.stxx.stiot2.gateway;

import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.constants.DriverType;
import com.stxx.stiot2.domain.Gateway;
import com.stxx.stiot2.gateway.example.MqttServer;
import com.stxx.stiot2.gateway.example.TcpServer;
import com.stxx.stiot2.gateway.face.GatewayServer;
import com.stxx.stiot2.service.GatewayService;
import com.stxx.stiot2.utils.JavaUtils;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.util.TopicUtil;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class GatewayUtils {
    public static final Map<String,GatewayServer> servers = new HashMap<String,GatewayServer>();
    public static final Map<String,String> topics = new HashMap<>();
    @Inject
    GatewayService gatewayService;
    @Init
    public void start(){
        List<Gateway> list = null;
        try {
            list = gatewayService.listActive();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (list != null) {
            list.forEach(this::initGateway);
        }
    }

    public void initGateway(Gateway gateway) {
        try {
            GatewayServer server = null;
            //server = (GatewayServer) JavaUtils.getClassInstance(gateway.getDriverClass());
           if(StrUtil.equals(gateway.getCode(),"tcp001")){
               server = new TcpServer();
           }else{
               server = (GatewayServer) JavaUtils.getClassInstance(gateway.getDriverClass());
           }

            server.init(gateway);
            servers.put(gateway.getCode(), server);
            if(gateway.getDriverType()== DriverType.MQTT){
                topics.put(gateway.getCode(),gateway.getParams().getSubTopic());
            }
            log.info("初始化网关{}({}) 成功", gateway.getName(), gateway.getCode());
        }catch (Exception ex){
            log.error(ex.getMessage());
        }
    }

    public GatewayServer getGateway(String gatewayCode) {
        if(servers.containsKey(gatewayCode)) {
            return servers.get(gatewayCode);
        }
        return null;
    }

    public GatewayServer getGatewayByTopic(String topic) {
        for(Map.Entry<String,String> entry : topics.entrySet()) {
            if(TopicUtil.match(entry.getValue(),topic)){
                return servers.get(entry.getKey());
            }
        }
        return null;
    }

    public void remove(String gatewayCode) {
        if(servers.containsKey(gatewayCode)) {
            GatewayServer server = servers.get(gatewayCode);
            server.close();
            servers.remove(gatewayCode);
            topics.remove(gatewayCode);
        }
    }
}
